<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="平台" prop="platformId">
        <el-input v-model="formData.platformId" placeholder="请输入平台编号" />
      </el-form-item>
      <el-form-item label="店铺" prop="storeId">
        <el-input v-model="formData.storeId" placeholder="请输入店铺编号" />
      </el-form-item>
      <el-form-item label="本地产品" prop="localProductId">
        <el-input v-model="formData.localProductId" placeholder="请输入本地产品ID" />
      </el-form-item>
      <el-form-item label="本地SKU" prop="localSku">
        <el-input v-model="formData.localSku" placeholder="请输入本地SKU" />
      </el-form-item>
      <el-form-item label="平台产品" prop="platformProductId">
        <el-input v-model="formData.platformProductId" placeholder="请输入平台产品ID" />
      </el-form-item>
      <el-form-item label="平台SKU" prop="platformSku">
        <el-input v-model="formData.platformSku" placeholder="请输入平台SKU" />
      </el-form-item>
      <el-form-item label="Listing ID" prop="platformListingId">
        <el-input v-model="formData.platformListingId" placeholder="请输入平台listing ID" />
      </el-form-item>
      <el-form-item label="ASIN" prop="platformAsin">
        <el-input v-model="formData.platformAsin" placeholder="请输入平台ASIN（Amazon）" />
      </el-form-item>
      <el-form-item label="商品ID" prop="platformItemId">
        <el-input v-model="formData.platformItemId" placeholder="请输入平台商品ID（eBay等）" />
      </el-form-item>
      <el-form-item label="变体ID" prop="platformVariantId">
        <el-input v-model="formData.platformVariantId" placeholder="请输入平台变体ID（Shopify等）" />
      </el-form-item>
      <el-form-item label="映射状态" prop="mappingStatus">
        <el-select v-model="formData.mappingStatus" placeholder="请选择映射状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_MAPPING_STATUS_PRODUCT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="同步状态" prop="syncStatus">
        <el-select v-model="formData.syncStatus" placeholder="请选择同步状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_SYNC_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="同步时间" prop="lastSyncTime">
        <el-date-picker
          v-model="formData.lastSyncTime"
          type="date"
          value-format="x"
          placeholder="选择最后同步时间"
        />
      </el-form-item>
      <el-form-item label="错误信息" prop="syncErrorMsg">
        <el-input v-model="formData.syncErrorMsg" placeholder="请输入同步错误信息" />
      </el-form-item>
      <el-form-item label="商品链接" prop="platformUrl">
        <el-input v-model="formData.platformUrl" placeholder="请输入平台商品链接" />
      </el-form-item>
      <el-form-item label="商品状态" prop="platformStatus">
        <el-select v-model="formData.platformStatus" placeholder="请选择平台商品状态">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="价格" prop="platformPrice">
        <el-input v-model="formData.platformPrice" placeholder="请输入平台价格" />
      </el-form-item>
      <el-form-item label="货币" prop="platformCurrency">
        <el-input v-model="formData.platformCurrency" placeholder="请输入平台货币" />
      </el-form-item>
      <el-form-item label="库存" prop="platformInventory">
        <el-input v-model="formData.platformInventory" placeholder="请输入平台库存数量" />
      </el-form-item>
      <el-form-item label="自动同步" prop="autoSync">
        <el-select v-model="formData.autoSync" placeholder="请选择是否自动同步">
          <el-option
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="String(dict.value)"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'
import { PlatformProductMappingApi, PlatformProductMappingVO } from '@/api/crossborder/platformproductmapping'

/** 跨境电商平台产品映射 表单 */
defineOptions({ name: 'PlatformProductMappingForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  platformId: undefined,
  storeId: undefined,
  localProductId: undefined,
  localSku: undefined,
  platformProductId: undefined,
  platformSku: undefined,
  platformListingId: undefined,
  platformAsin: undefined,
  platformItemId: undefined,
  platformVariantId: undefined,
  mappingStatus: undefined,
  syncStatus: undefined,
  lastSyncTime: undefined,
  syncErrorMsg: undefined,
  platformUrl: undefined,
  platformStatus: undefined,
  platformPrice: undefined,
  platformCurrency: undefined,
  platformInventory: undefined,
  autoSync: undefined,
})
const formRules = reactive({
  platformId: [{ required: true, message: '平台编号不能为空', trigger: 'blur' }],
  storeId: [{ required: true, message: '店铺编号不能为空', trigger: 'blur' }],
  localProductId: [{ required: true, message: '本地产品ID不能为空', trigger: 'blur' }],
  localSku: [{ required: true, message: '本地SKU不能为空', trigger: 'blur' }],
  mappingStatus: [{ required: true, message: '映射状态（0未映射 1已映射 2映射失败 3已下架）不能为空', trigger: 'blur' }],
  syncStatus: [{ required: true, message: '同步状态（0未同步 1同步中 2同步成功 3同步失败）不能为空', trigger: 'blur' }],
  autoSync: [{ required: true, message: '是否自动同步不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PlatformProductMappingApi.getPlatformProductMapping(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlatformProductMappingVO
    if (formType.value === 'create') {
      await PlatformProductMappingApi.createPlatformProductMapping(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlatformProductMappingApi.updatePlatformProductMapping(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    platformId: undefined,
    storeId: undefined,
    localProductId: undefined,
    localSku: undefined,
    platformProductId: undefined,
    platformSku: undefined,
    platformListingId: undefined,
    platformAsin: undefined,
    platformItemId: undefined,
    platformVariantId: undefined,
    mappingStatus: undefined,
    syncStatus: undefined,
    lastSyncTime: undefined,
    syncErrorMsg: undefined,
    platformUrl: undefined,
    platformStatus: undefined,
    platformPrice: undefined,
    platformCurrency: undefined,
    platformInventory: undefined,
    autoSync: undefined,
  }
  formRef.value?.resetFields()
}
</script>